package com.mohe.shanpao.netty;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class EchoClient {

	public static void main(String[] args) throws InterruptedException, IOException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
					pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
//					pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//					pipeline.addLast("decoder", new StringDecoder());
//				    pipeline.addLast("encoder", new StringEncoder());
					
					pipeline.addLast("decoder",new MessageDecoder());
					pipeline.addLast("encoder", new MessageEncoder());
					
				    pipeline.addLast(new EchoClientHandler(256));
				}
			});

//			 ChannelFuture f = bootstrap.connect("localhost", 9009).sync();
//			 f.channel().closeFuture().sync();
			
			Channel channel = bootstrap.connect("localhost", 9009).sync().channel();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String msg = null;
			while (!"bye".equals(msg)) {
				msg = in.readLine();
//				ByteBuf buf = channel.alloc().buffer();
//				buf.writeBytes(msg.getBytes());
//				channel.write(buf);
//				channel.flush();
				
//				channel.write(msg + "\n");
//				channel.flush();
				
				
				Message m = new Message();
				m.setValue(msg);
				channel.writeAndFlush(m);
				
			}

		} finally {
			group.shutdownGracefully();
		}
	}

}
